/*
 * @Author: yjp
 * @Date: 2022-03-24 09:27:39
 */
import React, { useRef, useState } from 'react';
import type { ActionType } from '@ant-design/pro-table';
import { ProColumns } from '@ant-design/pro-table';
import {
  addUser,
  deleteUser,
  getUser,
  listUser,
  updatePassword,
  updateRoles,
  updateUser,
} from './api';
import { handleRemove, handleUpdate } from '@/utils/actions';
import MegaCreateForm from '@/compoments/MegaCreateForm';
import MegaUpdateForm from '@/compoments/MegaUpdateForm';
import MegaTable from '@/compoments/MegaTable';
import { UserEntity } from './entities';
import { formChildren, UpdateRolesForm } from './form';
import { ModalForm } from '@ant-design/pro-form';
import { PasswordForm } from '@/compoments/UserForm/PasswordForm';

export default () => {
  const tableActionRef = useRef<ActionType>();

  const [createModalVisible, handleCreateModalVisible] = useState<boolean>(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [passwordModalVisible, handlePasswordModalVisible] = useState<boolean>(false);
  const [roleModalVisible, handleRoleModalVisible] = useState<boolean>(false);

  const [currentEntity, setCurrentEntity] = useState<UserEntity>();

  const tableColumns: ProColumns<UserEntity>[] = [
    {
      title: '账号',
      dataIndex: 'username',
    },
    {
      title: '姓名',
      dataIndex: 'name',
      render: (text, record, _, action) => `${record.first_name}${record.last_name}`
    },
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <a
          key="edit"
          onClick={() => {
            setCurrentEntity(record);
            handleUpdateModalVisible(true);
          }}
        >
          编辑
        </a>,
        <a
          key="roles"
          onClick={async () => {
            setCurrentEntity(record);
            handleRoleModalVisible(true);
          }}
        >
          分配角色
        </a>,
        <a
          key="password"
          onClick={async () => {
            setCurrentEntity(record);
            handlePasswordModalVisible(true);
          }}
        >
          修改密码
        </a>,
        <a
          key="delete"
          onClick={async () => {
            await handleRemove(record.id, deleteUser);
            tableActionRef.current?.reloadAndRest?.();
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  return (
    <div style={{ paddingTop: 16 }}>
      <MegaTable
        handleCreateModalVisible={handleCreateModalVisible}
        columns={tableColumns}
        actionRef={tableActionRef}
        title={'用户'}
        tableRequest={listUser}
        deleteRowAction={deleteUser}
        search={false}
      />
      <MegaCreateForm
        handleModalVisible={handleCreateModalVisible}
        actionRef={tableActionRef}
        modalVisible={createModalVisible}
        title={'新增用户'}
        addEntityAction={addUser}
      >
        {formChildren(true)}
      </MegaCreateForm>

      <MegaUpdateForm
        handleModalVisible={handleUpdateModalVisible}
        actionRef={tableActionRef}
        modalVisible={updateModalVisible}
        currentEntity={currentEntity}
        title={'编辑用户'}
        getEntityAction={getUser}
        updateEntityAction={updateUser}
      >
        {formChildren(false)}
      </MegaUpdateForm>
      <ModalForm
        title={'分配角色'}
        visible={roleModalVisible}
        onVisibleChange={handleRoleModalVisible}
        modalProps={{
          destroyOnClose: true,
        }}
        request={currentEntity ? () => getUser(currentEntity.id) : undefined}
        onFinish={async (value) => {
          const { groups } = value;
          const newValue = { group_id: groups.map((item) => item.id).join(',') }
          const success = await handleUpdate(currentEntity?.id, newValue, updateRoles);
          if (success) {
            handleRoleModalVisible(false);
          }
        }}
      >
        <UpdateRolesForm />
      </ModalForm>
      <ModalForm
        title={'修改密码'}
        visible={passwordModalVisible}
        onVisibleChange={handlePasswordModalVisible}
        modalProps={{
          destroyOnClose: true,
        }}
        onFinish={async (value) => {
          const { new_password, need_renew = false } = value;
          const newValue = { new_password, need_renew }
          const success = await handleUpdate(currentEntity?.id, newValue, updatePassword);
          if (success) {
            handlePasswordModalVisible(false);
          }
        }}
      >
        <PasswordForm isPersonal={false}/>
      </ModalForm>
    </div>
  );
}
